package org.osll.tictactoe.transport.rmi.client;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.osll.tictactoe.Control;
import org.osll.tictactoe.CurrentMove;
import org.osll.tictactoe.Move;
import org.osll.tictactoe.Size;
import org.osll.tictactoe.Team;
import org.osll.tictactoe.engine.MoveImpl;
import org.osll.tictactoe.transport.DefaultOptions;


public class ControlImpl implements Control {

	private org.osll.tictactoe.transport.rmi.Control server = null;
	private String name;
	private Team team;
	
	public ControlImpl(String serviceName, String user, Team team) {
		System.out.println("RMI connecting" + serviceName);
		this.name = user;
		this.team = team;
		try {
			Registry registry = LocateRegistry.getRegistry(DefaultOptions.getInstance().getHost());
			server = (org.osll.tictactoe.transport.rmi.Control)registry.lookup(serviceName);
			server.loginUser(user, team);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			throw new IllegalStateException("Couldn't connect to registry");
		}
	}

	@Override
	public void disconnect() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Move getApponentMove() {
		try {
			Team t;
			if(team == Team.X)
				t = Team.O;
			else
				t = Team.X;			
			return server.getApponentMove(t);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getApponentName() {
		try {
			Team t;
			if(team == Team.X)
				t = Team.O;
			else
				t = Team.X;
			return server.getApponentName(t);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public CurrentMove getMoveEndTime() {
		try {
			return server.getMoveEndTime();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Size getSize() {
		try {
			return server.getSize();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean isOver() {
		try {
			return server.isOver();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean isStarted() {
		try {
			return server.isStarted();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void makeMove(int row, int col) {
		try {
			server.makeMove(new MoveImpl(row, col,team));
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
